<template>
  <vxe-modal
    resize
    esc-closable
    width="55%"
    height="80%"
    showFooter
    v-model="formVisible"
    @hide="formClose"
    :loading="formLoading"
  >
    <template slot="title">
      <span>编码规则表单</span>
    </template>
    <template>
      <el-scrollbar class="scrollbar-handle">
        <!--主体 -->
        <vxe-form
          ref="firstForm"
          title-width="80"
          title-align="right"
          :data="formEntity"
          :rules="rules"
          span="12"
        >
          <vxe-form-item
            title="编号"
            field="B_EnCode"
            :title-suffix="{ message: '编号不能重复！', icon: 'fa fa-exclamation-circle' }"
          >
            <el-input v-model="formEntity.B_EnCode" placeholder="请输入" clearable></el-input>
          </vxe-form-item>
          <vxe-form-item
            title="名称"
            field="B_Name"
            :title-suffix="{ message: '名称不能重复！', icon: 'fa fa-exclamation-circle' }"
          >
            <el-input v-model="formEntity.B_Name" placeholder="请输入" clearable></el-input>
          </vxe-form-item>
          <vxe-form-item title="说明" field="B_Description" span="24">
            <el-input v-model="formEntity.B_Description" placeholder="请输入" clearable></el-input>
          </vxe-form-item>
        </vxe-form>
        <!-- 可编辑表格 -->
        <vxe-grid
          ref="editTable"
          :height="tableHeight"
          :columns="tableColumn"
          :data="tableData"
          :context-menu="{body: {options: bodyMenus}}"
          :edit-config="{activeMethod: activeCellMethod}"
          :edit-rules="rules"
          :highlight-current-row="false"
          :mouse-config="{selected: true}"
          :keyboard-config="{isArrow: true, isDel: true, isEnter:true, isTab: true, isEdit: true}"
          :sync-resize="formVisible"
        ></vxe-grid>
      </el-scrollbar>
    </template>
    <template slot="footer">
      <el-button type="primary" v-form-validate="formSubmit">保存</el-button>
      <el-button @click="formVisible=false">取消</el-button>
    </template>
  </vxe-modal>
</template>

<script> 
import { CodeRule } from "@/api";
export default {
  props: {},
  data() {
    return {
      //表单可见
      formVisible: false,
      //表单加载中
      formLoading: false,
      //存放表单ref数组
      formArr: ["firstForm", "editTable"],
      //表单实体
      formEntity: {},
      //表单验证规则（规则键必须和表单键一致）
      rules: {
        B_EnCode: [
          {
            required: true,
            validator: ({ itemValue, property }) => {
              return new Promise((resolve, reject) => {
                if (this.util.validateNull(itemValue)) {
                  reject(new Error("不能为空！"));
                } else {
                  CodeRule.ValidateExist({
                    id: this.formEntity.B_RuleId,
                    field: property,
                    value: itemValue,
                  })
                    .then((res) => {
                      resolve();
                    })
                    .catch((err) => {
                      reject(new Error("规则编码已存在！"));
                    });
                }
              });
            },
          },
        ],
        B_Name: [
          {
            required: true,
            validator: ({ itemValue, property }) => {
              return new Promise((resolve, reject) => {
                if (this.util.validateNull(itemValue)) {
                  reject(new Error("不能为空！"));
                } else {
                  CodeRule.ValidateExist({
                    id: this.formEntity.B_RuleId,
                    field: property,
                    value: itemValue,
                  })
                    .then((res) => {
                      resolve();
                    })
                    .catch((err) => {
                      reject(new Error("规则名称已存在！"));
                    });
                }
              });
            },
          },
        ],
        B_ItemType: [{ required: true, message: "不能为空" }],
        B_FormatStr: [{ required: true, message: "不能为空" }],
      },
      /* vxe-grid */
      tableHeight: 400, //表格高度
      tableData: [], //模块按钮表格实体
      //列配置
      tableColumn: [
        {
          field: "B_ItemType",
          title: "前缀",
          editRender: {
            name: "ElSelect",
            options: this.util.getDataItemList("ItemType"),
            optionProps: { label: "label", value: "value" },
            events: { change: this.selChangeEvent },
          },
        },
        {
          field: "B_FormatStr",
          title: "格式",
          editRender: {},
        },
        {
          field: "B_StepValue",
          title: "步长",
          editRender: { name: "ElInputNumber", props: { min: 0 } },
        },
        {
          field: "B_InitValue",
          title: "初始值",
          editRender: { name: "ElInputNumber", props: { min: 0 } },
        },
        {
          field: "B_Description",
          title: "说明",
          editRender: { name: "ElInput", autoselect: true },
        },
      ],
      //可编辑表格快捷菜单
      bodyMenus: [
        [
          {
            code: "insert",
            name: "插入",
            prefixIcon: "el-icon-plus",
          },
          {
            code: "clear",
            name: "清除",
            prefixIcon: "fa fa-eraser",
          },
          {
            code: "remove",
            name: "删除",
            prefixIcon: "el-icon-delete",
          },
        ],
      ],
    };
  },
  created() {
    //初始化
    this.init();
  },
  methods: {
    //初始化
    init() {},
    //表单开启
    formOpen(row) {
      //打开表单
      this.formVisible = this.formLoading = true;
      if (!row) {
        //新增
        this.formLoading = false;
      } else {
        //编辑
        this.formEntity = JSON.parse(JSON.stringify(row));
        //加载表体
        CodeRule.GetFormatList(row.B_RuleId).then((res) => {
          this.tableData = res;
          this.formLoading = false;
        });
      }
    },
    //表单提交
    formSubmit() {
          //更新当前表格数据
          this.tableData = this.$refs["editTable"].getTableData().fullData;
          //验证通过
          CodeRule.Save({
            codeRuleEntity: this.formEntity,
            formatList: this.tableData,
          }).then((res) => {
            this.formVisible = false; //关闭弹窗
            this.$emit("refresh"); //刷新表格
          });
    },
    //表单关闭
    formClose() {
      //清除表单验证
      this.util.formClearValid(this.formArr);
      //数据归位
      Object.assign(this.$data, this.$options.data.call(this))
    },
    //可编辑表格联动下拉
    selChangeEvent({ row }) {
      // 切换时更新级联的下拉数据
      switch (row.B_ItemType) {
        case `2`:
          row.B_FormatStr = "";
          row.B_StepValue = 1;
          row.B_InitValue = 1;
          break;
        case `3`:
          row.B_FormatStr = "组织编号";
          row.B_StepValue = "";
          row.B_InitValue = "";
          break;
        case `4`:
          row.B_FormatStr = "部门编号";
          row.B_StepValue = "";
          row.B_InitValue = "";
          break;
        case `5`:
          row.B_FormatStr = "用户编号";
          row.B_StepValue = "";
          row.B_InitValue = "";
          break;
        default:
          row.B_FormatStr = "";
          row.B_StepValue = "";
          row.B_InitValue = "";
          break;
      }
    },
    //单元格是否允许编辑
    activeCellMethod({ row, rowIndex, column, columnIndex }) {
      //单元格格式渲染
      switch (row.B_ItemType) {
        case `1`:
          this.tableColumn[1].editRender = {
            name: "ElSelect",
            options: this.util.getDataItemList("DateFormat"),
            optionProps: { label: "B_ItemName", value: "B_ItemValue" },
          };
          break;
        case `2`:
          this.tableColumn[1].editRender = {
            name: "ElSelect",
            options: this.util.getDataItemList("SerFormat"),
            optionProps: { label: "B_ItemName", value: "B_ItemValue" },
          };
          break;
        default:
          this.tableColumn[1].editRender = {
            name: "ElInput",
            autoselect: true,
          };
          break;
      }
      //单元格禁止编辑
      if (
        columnIndex === 1 &&
        (row.B_ItemType === `3` ||
          row.B_ItemType === `4` ||
          row.B_ItemType === `5`)
      ) {
        return false; //格式
      } else if (
        (columnIndex === 2 || columnIndex === 3) &&
        row.B_ItemType !== `2`
      ) {
        return false; //步长、初始值
      }

      return true;
    },
  },
};
</script>
